﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using ST.Common.Data;
using ST.Common.Util;
using ST.Common.Util.Model;
using ST.Buz.Base;
using ST.Buz.Base.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using ST.Common.Util.Mvc;
using ST.Buz.Base.ViewModel;
using ST.WX.MP.TplMsg;
using ST.WX.MP.TplMsg.Model;
using ST.Buz.Base.Enums;

namespace ST.Buz.Service
{
	public partial interface IServiceWXTplMsgConfig
	{
		/// <summary>
		/// 分页列表
		/// </summary>
		PageData GetPageList(VMS_WX_TplMsgConfig searchModel, UserSession sessionCurrent);

		/// <summary>
		/// 新增或修改信息
		/// </summary>
		int AddOrUpdate(WX_TplMsgConfig model, UserSession sessionCurrent);

		/// <summary>
		/// 删除部门
		/// </summary>
		/// <param name="id"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		bool Delete(int id, UserSession sessionCurrent);

		/// <summary>
		/// 获取查看时的详细信息
		/// </summary>
		/// <param name="id"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		WX_TplMsgConfig GetViewDetail(int id, UserSession sessionCurrent);

		/// <summary>
		/// 获取编辑时的详细信息
		/// </summary>
		/// <param name="id"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		WX_TplMsgConfig GetEditDetail(int id, UserSession sessionCurrent);

		bool Sync(string appID, WXTplMsgListResult ret, UserSession sessionCurrent);
	}

	public partial class ServiceWXTplMsgConfig
	{
		private readonly IServiceSysLog serviceSysLog;
		public ServiceWXTplMsgConfig(BuzContext ctx,
			IServiceSysLog _serviceSysLog,
			ILogger<ServiceWXTplMsgConfig> log)
		{
			serviceSysLog = _serviceSysLog;

			context = ctx;
			logger = log;
		}

		/// <summary>
		/// 新增或修改信息
		/// </summary>
		public int AddOrUpdate(WX_TplMsgConfig model, UserSession sessionCurrent)
		{
			try
			{
				if (model == null)
				{
					throw new BuzException("参数不能为空");
				}
				if (model.ID > 0)
				{
					Update(model);
				}
				else
				{
					model.AddDate = DateTime.Now;
					model.AddManID = sessionCurrent.UserID;
					model.AddManName = sessionCurrent.UserName;

					model.ID = Add(model);
				}
				return model.ID;
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (DbUpdateException ex)
			{
				logger.LogError(ex.InnerException ?? ex, "保存对象信息出错");
				throw new BuzException("数据库保存失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "保存对象信息出错");
				throw new BuzException("保存失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
		}

		/// <summary>
		/// 获取查看时的详细信息
		/// </summary>
		/// <param name="id"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		public WX_TplMsgConfig GetViewDetail(int id, UserSession sessionCurrent)
		{
			try
			{
				var result = (from m in context.WXTplMsgConfig
							  where m.ID == id
							  select m).AsNoTracking().SingleOrDefault();
				if (result == null)
				{
					throw new BuzException("参数有误");
				}
				return result;
			}
			catch (ArgumentException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "获取对象信息出错");
				throw new BuzException("获取对象信息失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
		}

		/// <summary>
		/// 获取编辑时的详细信息
		/// </summary>
		/// <param name="id"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		public WX_TplMsgConfig GetEditDetail(int id, UserSession sessionCurrent)
		{
			return GetViewDetail(id, sessionCurrent);
		}

		/// <summary>
		/// 分页列表
		/// </summary>
		public PageData GetPageList(VMS_WX_TplMsgConfig searchModel, UserSession sessionCurrent)
		{
			PageData result = null;
			try
			{
				searchModel.Validate();

				var query = (from m in context.WXTplMsgConfig
							 join a in context.WXAppConfig on m.AppID equals a.AppID
							 select new
							 {
								 m.Title,
								 m.Code,
								 m.AppID,
								 m.ID,
								 m.Type,
								 m.Example,
								 m.AddDate,
								 m.AddManID,
								 m.AddManName,
								 m.Comment,
								 a.OrgID,
								 m.Tpl,
								 m.Sort,
								 m.StateNow,
							 }).AsNoTracking();
				if (!string.IsNullOrEmpty(searchModel.title))
				{
					query = query.Where(m => EF.Functions.Like(m.Title, "%" + searchModel.title + "%"));
				}
				if (!string.IsNullOrEmpty(searchModel.code))
				{
					query = query.Where(m => m.Code == searchModel.code);
				}
				if (!string.IsNullOrEmpty(searchModel.appid))
				{
					query = query.Where(m => m.AppID == searchModel.appid);
				}
				if (searchModel.ids != null && searchModel.ids.Length > 0)
				{
					query = query.Where(m => searchModel.ids.Contains(m.ID));
				}
				if (searchModel.type.HasValue)
				{
					query = query.Where(m => m.Type == searchModel.type.Value);
				}
				if (searchModel.orgids != null && searchModel.orgids.Length > 0)
				{
					query = searchModel.orgids.Length == 1 ? query.Where(m => m.OrgID == searchModel.orgids[0]) : query.Where(m => searchModel.orgids.Contains(m.OrgID));
				}
				switch (searchModel.sortby)
				{
					default:
						query = query.OrderByDescending(e => e.ID);
						break;
				}
				result = new PageData(searchModel.pnum.Value, searchModel.psize.Value);
				result.Load(query);
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "获取分页数据出错");
				throw new BuzException("获取分页数据失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
			return result;
		}

		/// <summary>
		/// 删除参数
		/// </summary>
		/// <param name="id"></param>
		/// <param name="sessionCurrent"></param>
		/// <returns></returns>
		public bool Delete(int id, UserSession sessionCurrent)
		{
			bool success = false;
			try
			{
				//if (logger.IsEnabled(LogLevel.Debug))
				//{
				//	logger.LogDebug($"参数->id:{id}，state:{state}，remark:{remark}");
				//}
				if (sessionCurrent == null)
				{
					throw new BuzException("用户会话不能为空");
				}

				using (var trans = context.Database.BeginTransaction())
				{
					try
					{
						#region 事务具体操作
						DateTime dtNow = DateTime.Now;
						string ip = GetRequestIP();

						var modelOld = Get(id, true);
						Delete(modelOld);

						serviceSysLog.Add(sessionCurrent, ip, $"删除模板消息日志信息，原信息：", modelOld, dtNow);
						#endregion

						trans.Commit();
					}
					catch (Exception ex)
					{
						trans.Rollback();
						throw ex.InnerException ?? ex;
					}
				}

				success = true;
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "删除模板消息日志信息出错");
				throw new BuzException("删除模板消息日志信息失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
			return success;
		}

		public bool Sync(string appID, WXTplMsgListResult ret, UserSession sessionCurrent)
		{
			bool success = false;
			try
			{
				//if (logger.IsEnabled(LogLevel.Debug))
				//{
				//	logger.LogDebug($"参数->id:{id}，state:{state}，remark:{remark}");
				//}
				if (sessionCurrent == null)
				{
					throw new BuzException("用户会话不能为空");
				}
				if (string.IsNullOrEmpty(appID))
				{
					throw new BuzException("应用ID不能为空");
				}
				if (ret == null)
				{
					throw new BuzException("模板列表返回为空");
				}
				using (var trans = context.Database.BeginTransaction())
				{
					try
					{
						#region 事务具体操作
						DateTime dtNow = DateTime.Now;
						string ip = GetRequestIP();


						var tpls = new List<WX_TplMsgConfig>();
						foreach (var t in ret.template_list)
						{
							tpls.Add(new WX_TplMsgConfig()
							{
								AppID = appID,
								Type = (int)TplMsgType.其他,
								Code = t.template_id,
								Title = t.title,
								//primary_industry=t.primary_industry,
								//deputy_industry=t.deputy_industry,
								Tpl = t.content,
								Example = t.example,
							});
						}
						var comparer = new WX_Compare_TplMsgConfig();
						var lstOld = context.WXTplMsgConfig.Where(m => m.AppID == appID).AsNoTracking().ToList();
						//var lstDelete = lstOld.Except(tpls, comparer);//找出删掉的
						var lstNew = tpls.Except(lstOld, comparer);//找出新的
						var lstUpdate = tpls.Intersect(lstOld, comparer);//找出需要更新的

						//foreach (var d in lstDelete)
						//{
						//	context.Database.ExecuteSqlInterpolated($"UPDATE WX_TplMsgConfig SET StateNow=(CASE WHEN StateNow={(int)WXTplState.正常} THEN {(int)WXTplState.已删除} ELSE StateNow END) WHERE AppID=${appID}");
						//}
						context.Database.ExecuteSqlInterpolated($"UPDATE WX_TplMsgConfig SET StateNow=(CASE WHEN StateNow={(int)WXTplState.正常} THEN {(int)WXTplState.已删除} ELSE StateNow END) WHERE AppID={appID}");

						foreach (var n in lstNew)
						{
							n.AddDate = dtNow;
							n.AddManID = sessionCurrent.UserID;
							n.AddManName = sessionCurrent.UserName;
							n.StateNow = (int)WXTplState.正常;
							context.WXTplMsgConfig.Add(n);
							context.SaveChanges();
						}

						foreach (var u in lstUpdate)
						{
							context.Database.ExecuteSqlInterpolated($"UPDATE WX_TplMsgConfig SET StateNow={(int)WXTplState.正常},Title={u.Title},Tpl={u.Tpl},Example={u.Example} WHERE Code={u.Code}");
						}
						//serviceSysLog.Add(sessionCurrent, ip, $"更新模板消息配置信息，原信息：", modelOld, dtNow);
						#endregion

						trans.Commit();
					}
					catch (Exception ex)
					{
						trans.Rollback();
						throw ex.InnerException ?? ex;
					}
				}

				success = true;
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "更新模板消息配置信息出错");
				throw new BuzException("更新模板消息配置信息失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
			return success;
		}
	}
}